package com.ming.consumemq.config;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.ming.common.util.ApplicationContextUtil;
import com.ming.mq.common.config.MingMqConfig;
import com.ming.mq.common.enums.ConsumeEntity;
import com.ming.mq.common.enums.MqParamMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Classname SystemMqConfig
 * @Description TODO
 * @Date 2021/1/13 15:59
 * @Created by yanming.fu
 */
@Slf4j
@Configuration
@Getter
@Setter
@ConditionalOnExpression("'ming-system'.equals('${spring.application.name}')")
public class SystemMqConfig {

    public static final String GROUP_ID = MqParamMapper.SYSTEM.getGroupId();

    @Bean(initMethod = "start", destroyMethod = "shutdown", name = "GID-ks-score")
    public ConsumerBean getConsumerBean() {
        return wrapperBean();
    }

    private ConsumerBean wrapperBean() {
        MingMqConfig mqConfig = ApplicationContextUtil.getBean(MingMqConfig.class);
        Properties mqProperty = mqConfig.getMqProperty();
        mqProperty.setProperty(PropertyKeyConst.GROUP_ID, GROUP_ID);
//      properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");

        log.info("初始化SystemMqConfig->consumer消费者：accessKey:{}， secretKey:{}， nameSrvAddr:{}， groupId:{}",
                mqProperty.get(PropertyKeyConst.AccessKey), mqProperty.get(PropertyKeyConst.SecretKey),
                mqProperty.get(PropertyKeyConst.NAMESRV_ADDR), mqProperty.getProperty(PropertyKeyConst.GROUP_ID));
        ConsumerBean consumerBean = new ConsumerBean();
        consumerBean.setProperties(mqProperty);

        Map<Subscription, MessageListener> subscriptionMap = new HashMap<>();
        List<ConsumeEntity> addList = MqParamMapper.getAddList(mqConfig.getApplicationName(), GROUP_ID);
        for (ConsumeEntity consumeEntity : addList) {
            MingMqConfig.addSubscription(subscriptionMap, consumeEntity.getTopic(), consumeEntity.getTag(), consumeEntity.getBeanName());
            log.info("监听消息如下: {}, {}, {}", consumeEntity.getTopic(), consumeEntity.getTag(), consumeEntity.getBeanName());
        }
        consumerBean.setSubscriptionTable(subscriptionMap);
        return consumerBean;
    }
}
